package com.example.lock;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    Thread connect_service;
    Button button_open;
    Button button_connect;
    TextView textView_status;
    Socket s;
    String ip="169.254.220.126";
    int port=4000;
    int connect_ok=0;
    int status=0;
    StringBuffer tx;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button_open=findViewById(R.id.button_open);
        button_connect=findViewById(R.id.button_connect);
        textView_status=findViewById(R.id.textview_status);
        tx=new StringBuffer("0");

        button_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(status==0){
                    try{
                        connect_service.start();
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        connect_service=new Thread(new Runnable() {
            @Override
            public void run() {
                status=1;
                try {
                    s=new Socket(ip,port);
                    textView_status.setText("成功");
                    connect_ok=1;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(connect_ok==0){
                    port=port+1;//尝试自动端口号
                    textView_status.setText(port);
                }
            }
        });
        button_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (connect_ok==1){
                    tx.replace(0,1,"1");
                    send();
                }
            }
        });
    }
    private void send(){
        OutputStream outputStream=null;
        try {
            String send_buff=String.valueOf(tx);
            outputStream=s.getOutputStream();
            outputStream.write(send_buff.getBytes());
            outputStream.flush();
            tx.replace(0,1,"0");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}